import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_todolist/db/table/user_table.dart';
import 'package:flutter_todolist/pages/auth/auth_login.dart';
import 'package:flutter_todolist/pages/home/task_controller.dart';
import 'package:flutter_todolist/pages/home/task_type_controller.dart';
import 'package:flutter_todolist/pages/info_setting/info_setting.dart';
import 'package:flutter_todolist/pages/on_boarding/onboarding.dart';
import 'package:flutter_todolist/utils/get_storage.dart';
import 'package:flutter_todolist/widgets/app_button.dart';
import 'package:get/get.dart';

import 'package:flutter_todolist/pages/home/bottomNavigation.dart';
import 'package:flutter_todolist/pages/widgets/fab.dart';
import 'package:flutter_todolist/pages/home/task_overview.dart';
import 'package:flutter_todolist/pages/home/task_timeline.dart';
import 'package:flutter_todolist/util.dart';
import 'package:flutter_todolist/widgets/app_bars.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  int bottomNavigationBarIndex = 0;
  PageController pageCtrl = PageController(initialPage: 0);
  TaskController taskCtrl = Get.put(TaskController());
  TaskTypeController taskTypeCtrl = Get.put(TaskTypeController());
  bool showReminder = true;

  late User userInfo;

  // final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    userInfo = User.fromJson(AppStorage().read(AppStorage.UserInfo));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: content(),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: customFab(context),
      bottomNavigationBar: BottomNavigationBarApp(context, bottomNavigationBarIndex, (index) {
        setState(() {
          bottomNavigationBarIndex = index;
        });
        pageCtrl.animateToPage(
          index,
          duration: const Duration(milliseconds: 500),
          curve: Curves.fastLinearToSlowEaseIn,
        );
      }),
    );
  }

  Widget content() {
    return Scaffold(
      body: Column(
        children: [
          Container(
            child: Stack(
              children: [
                Container(
                  height: showReminder ? (Get.statusBarHeight.h + 100.h) : (Get.statusBarHeight),
                  decoration: const BoxDecoration(
                      gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [CustomColors.HeaderBlueDark, CustomColors.HeaderBlueLight],
                  )),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    CustomPaint(
                      painter: CircleOne(),
                    ),
                    CustomPaint(
                      painter: CircleTwo(),
                    ),
                  ],
                ),
                Positioned(
                    left: 0,
                    right: 0,
                    top: 0,
                    child: SafeArea(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          // SizedBox(height: Get.statusBarHeight),

                          topBar(),

                          todayReminder()
                        ],
                      ),
                    ))
              ],
            ),
          ),
          Expanded(child: pageContent())
        ],
      ),
    );
  }

  Widget topBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15.w),
      height: 40.h,
      child: Row(
        children: [
          // Icon(Icons.arrow_back_ios_new_rounded, size: 25.r, color: Colors.white),
          // SizedBox(width: 10.w),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                'Hello ${userInfo.name}!',
                style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: Colors.white),
              ),
              // Text(
              //   'Today you have 9 tasks',
              //   style: TextStyle(fontSize: 10, fontWeight: FontWeight.w300, color: Colors.white),
              // ),
            ],
          ),
          const Expanded(child: SizedBox()),
          avatar(),
        ],
      ),
    );
  }

  Widget todayReminder() {
    return showReminder
        ? Container(
            height: 80.h,
            margin: const EdgeInsets.symmetric(vertical: 15, horizontal: 20),
            padding: const EdgeInsets.fromLTRB(15, 5, 15, 0),
            decoration: BoxDecoration(
              color: CustomColors.HeaderGreyLight,
              borderRadius: BorderRadius.circular(5.0),
            ),
            // width: double.maxFinite,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                  // color: Colors.orange,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      const Text(
                        'Today Reminder',
                        style: TextStyle(color: Colors.white, fontSize: 17, fontWeight: FontWeight.w600),
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      Text(
                        'Today you have ${getTodayTaskCount()} tasks',
                        style: TextStyle(fontSize: 10, fontWeight: FontWeight.w300, color: Colors.white),
                      ),
                    ],
                  ),
                ),
                // Container(
                //   width: MediaQuery.of(context).size.width / 2.9,
                // ),
                Container(
                  // color: Colors.grey,
                  child: Image.asset(
                    'assets/images/bell-left.png',
                    scale: 1.3,
                  ),
                ),
                // .animate(
                //     autoPlay: true,
                //     onComplete: (aniCtrl) {
                //       aniCtrl.reverse();
                //       // aniCtrl.repeat();
                //     }
                // )
                // .rotate(begin: -0.2, end: 0.2, duration: Duration(seconds: 1), alignment: Alignment(0.5,-1))
                // .rotate(begin: -0.2, end: 0.0, duration: Duration(milliseconds: 500), delay: Duration(seconds: 1)),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    setState(() {
                      showReminder = false;
                    });
                  },
                  child: Container(
                    margin: EdgeInsets.only(bottom: 80),
                    child: const Icon(
                      Icons.clear,
                      color: Colors.white,
                      size: 18.0,
                    ),
                  ),
                ),
              ],
            ),
          ).animate().scale()
        : SizedBox(height: 10.h);
  }

  Widget pageContent() {
    return PageView(
      controller: pageCtrl,
      children: const [TaskTimeLine(), TaskOverView()],
    );
  }

  int getTodayTaskCount() {
    int count = 0;
    int today = DateTime.now().day;
    for (var element in taskCtrl.taskList) {
      int taskDay = DateTime.fromMillisecondsSinceEpoch(element.expiresTime!).day;
      if (today == taskDay) {
        count++;
      }
    }
    return count;
  }

  Widget drawerContent() {
    return Container(
      width: Get.width,
      child: InfoSetting(userInfo: userInfo),
      // child: Column(
      //   children: [
      //     AppButton(
      //       content: '退出登录',
      //       onTap: () {
      //         // Get.offAll(() => OnBoarding());
      //         Get.offAll(() => AuthPage());
      //       },
      //     )
      //   ],
      // ),
    );
  }

  Widget avatar() {
    return GestureDetector(
      onTap: () {
        // scaffoldKey.currentState!.openEndDrawer();
        Get.to(() => InfoSetting(userInfo: userInfo, logOut: true), transition: Transition.rightToLeft);
      },
      child: SizedBox(
        width: 30.r,
        height: 30.r,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(90),
          child: userInfo.avatar!.isNotEmpty
              ? Image.file(File(userInfo.avatar!), fit: BoxFit.cover)
              : Image.asset('assets/images/default_avatar.png', fit: BoxFit.cover),
        ),
      ),
    );
  }
}
